package com.gitee.slowcreator.http.executor;

import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.ServiceLoaderUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * http 执行器工厂
 * 参考hutool
 *
 * @author zxw
 * @date 2023/1/6 下午9:17
 */
@Slf4j
public class HttpExecutorFactory {

    /**
     * 根据用户引入的模板引擎jar，自动创建对应的分词引擎对象<br>
     * 获得的是单例的HttpExecutor
     *
     * @return 单例的HttpExecutor
     */
    public static HttpExecutor get(){

        return Singleton.get(HttpExecutor.class.getName(), HttpExecutorFactory::create);
    }

    /**
     * 根据用户引入的分词http请求jar，自动创建对应的对象
     *
     * @return {@link HttpExecutor}
     */
    public static HttpExecutor create() {
        final HttpExecutor engine = doCreate();
        log.info("Use [{}] http executor As Default.", StrUtil.removeSuffix(engine.getClass().getSimpleName(), "Executor"));
        return engine;
    }

    /**
     * 根据用户引入的分词http请求jar，自动创建对应的对象
     *
     * @return {@link HttpExecutor}
     */
    private static HttpExecutor doCreate() {

        final HttpExecutor engine = ServiceLoaderUtil.loadFirstAvailable(HttpExecutor.class);
        if(null != engine){
            return engine;
        }

        throw new RuntimeException("No tokenizer found ! Please add some tokenizer jar to your project !");
    }
}
